package com.kelvin.oocl.printer;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.TreeSet;

import com.kelvin.oocl.constart.SystemConstant;
import com.kelvin.oocl.pojo.Customer;
import com.kelvin.oocl.util.DateUtil;

public class FormatPrinterImpl implements FormatPrinter {

	@Override
	public String print(TreeSet<Customer> customers, String format) {
		StringBuilder sb = new StringBuilder();
		if("xml".equals(format)){
			sb.append("#------------------------All Customers sort by id-----------------------------\r\n");
			sb.append("  <customers>\r\n");
			for (Customer c : customers) {
				sb.append("     <customer id='"+c.getId()+"'>\r\n");
				sb.append("          <name>"+c.getName()+"</name>\r\n");
				sb.append("          <birthDate>"+DateUtil.dateToStr(c.getBirthDate(), "yyyy-MM-dd")+"</birthDate>\r\n");
				sb.append("          <sex>"+(c.isSex()==true ? "female":"male")+"</sex>\r\n");
				sb.append("          <email>"+c.getEmail()+"</email>\r\n");
				sb.append("     </customer"+c.getId()+"'>\r\n");
			}
			sb.append("  </customers>\r\n");
		}else if("line".equals(format)){
			sb.append("#-----------------------All Customers sort by birthDate--------------------------\r\n");
			for (Customer c : customers) {
				sb.append(" "+c.toString()+"\r\n");
			}
		}
		sb.append("#--------------------------------------------------------------------------------\r\n");
		return sb.toString();
	}

	@Override
	public String createXmlFile(TreeSet<Customer> customers,File target) throws IOException {
		BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target));
		String result = this.print(customers, "xml");
		out.write(result.getBytes());
		out.flush();
		out.close();
		return SystemConstant.OPERATION_SUCCESS;
	}

}
